<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单词填空游戏</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "SF Pro Icons", "Helvetica Neue", Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 40px 20px;
            text-align: center;
            background-color: #ffffff;
            color: #1d1d1f;
        }

        .score-board {
            display: flex;
            gap: 30px;
            justify-content: center;
            margin: 20px 0;
            font-size: 24px;
            color: #666;
        }

        .correct {
            color: #4CAF50;
        }

        .wrong {
            color: #f44336;
        }

        #sentence-display {
            font-size: 24px;
            line-height: 1.6;
            padding: 30px;
            margin: 30px auto;
            border-radius: 18px;
            background-color: #fbfbfd;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            text-align: left;
        }

        .blank {
            display: inline-block;
            width: 100px;
            height: 2px;
            background-color: #000;
            margin: 0 5px;
            vertical-align: middle;
        }

        .filled-word {
            display: inline-block;
            padding: 5px 15px;
            background-color: #e8f0fe;
            border-radius: 15px;
            margin: 0 5px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .filled-word:hover {
            background-color: #d0e0fd;
            transform: translateY(-2px);
        }

        #word-choices {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            justify-content: center;
            margin: 30px auto;
            padding: 20px;
            border-radius: 18px;
            background-color: #fbfbfd;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .word-choice {
            padding: 8px 20px;
            background-color: #0071e3;
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 16px;
        }

        .word-choice:hover {
            background-color: #0077ed;
            transform: translateY(-2px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        }

        .word-choice.used {
            background-color: #ccc;
            cursor: not-allowed;
        }

        .word-choice.wrong {
            animation: shake 0.5s;
            background-color: #ff4444;
        }

        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(10px); }
            75% { transform: translateX(-10px); }
        }

        .victory-effect {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 1000;
            display: none;
        }

        #word-input {
            width: 100%;
            max-width: 600px;
            height: 150px;
            margin: 20px auto;
            padding: 16px;
            font-size: 17px;
            line-height: 1.5;
            border-radius: 14px;
            border: 1px solid #d2d2d7;
            background-color: #fbfbfd;
            transition: all 0.3s ease;
            resize: none;
        }

        #word-input:focus {
            outline: none;
            border-color: #0071e3;
            box-shadow: 0 0 0 4px rgba(0, 113, 227, 0.1);
        }

        #generate-btn {
            font-size: 17px;
            font-weight: 400;
            padding: 12px 32px;
            margin: 20px;
            background-color: #0071e3;
            color: white;
            border: none;
            border-radius: 980px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        #generate-btn:hover {
            background-color: #0077ed;
            transform: scale(1.02);
        }
    </style>
</head>
<body>
    <audio id="correctSound" src="success.wav"></audio>
    <audio id="wrongSound" src="error.wav"></audio>
    <audio id="victorySound" src="game-fanfare.mp3"></audio>

    <div class="score-board">
        <div class="correct">正确：<span id="correctCount">0</span></div>
        <div class="wrong">错误：<span id="wrongCount">0</span></div>
    </div>

    <div id="sentence-display">请输入单词并点击生成按钮开始游戏</div>
    <div id="word-choices"></div>
    <textarea id="word-input" placeholder="请输入单词，每行一个">
house
apple
dog
cup
</textarea>
    <button id="generate-btn">生成句子</button>
    <div class="victory-effect" id="victoryEffect"></div>

    <script>
        const sentenceDisplay = document.getElementById('sentence-display');
        const wordChoices = document.getElementById('word-choices');
        const wordInput = document.getElementById('word-input');
        const generateBtn = document.getElementById('generate-btn');
        const correctSound = document.getElementById('correctSound');
        const wrongSound = document.getElementById('wrongSound');
        const victorySound = document.getElementById('victorySound');
        const victoryEffect = document.getElementById('victoryEffect');

        let words = [];
        let sentence = '';
        let filledWords = new Map();
        let correctCount = 0;
        let wrongCount = 0;

        // 彩带特效函数
        function createConfetti(container, count = 50) {
            if (!document.querySelector('#confetti-animations')) {
                const style = document.createElement('style');
                style.id = 'confetti-animations';
                style.textContent = `
                    @keyframes fall {
                        to {
                            top: 120%;
                            transform: rotate(${Math.random() * 720 + 360}deg);
                        }
                    }
                    @keyframes sway {
                        from { transform: translateX(-20px) rotate(-45deg); }
                        to { transform: translateX(20px) rotate(45deg); }
                    }
                `;
                document.head.appendChild(style);
            }

            for (let i = 0; i < count; i++) {
                const confetti = document.createElement('div');
                confetti.style.position = 'absolute';
                confetti.style.width = Math.random() * 10 + 5 + 'px';
                confetti.style.height = Math.random() * 20 + 10 + 'px';
                confetti.style.backgroundColor = `hsl(${Math.random() * 360}, 100%, 50%)`;
                confetti.style.left = Math.random() * 100 + '%';
                confetti.style.top = '-20px';
                confetti.style.opacity = '0.8';
                confetti.style.transform = `rotate(${Math.random() * 360}deg)`;
                confetti.style.borderRadius = '4px';
                container.appendChild(confetti);

                const fallDuration = Math.random() * 2 + 2;
                const swayDuration = Math.random() * 2 + 2;
                confetti.style.animation = `
                    fall ${fallDuration}s linear forwards,
                    sway ${swayDuration}s ease-in-out infinite alternate
                `;

                setTimeout(() => confetti.remove(), fallDuration * 1000);
            }
        }

        // 生成句子
        async function generateSentence(word) {
            try {
                // 显示加载状态
                let dots = '';
                const loadingInterval = setInterval(() => {
                    dots = dots.length >= 3 ? '' : dots + '.';
                    sentenceDisplay.textContent = 'AI出题中' + dots;
                }, 500);
                generateBtn.disabled = true;
                generateBtn.style.opacity = '0.6';
                generateBtn.style.cursor = 'not-allowed';

                const response = await fetch('http://localhost:5050/api/generateSentence', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ word })
                });
                const data = await response.json();

                // 恢复按钮状态
                generateBtn.disabled = false;
                generateBtn.style.opacity = '1';
                generateBtn.style.cursor = 'pointer';
                clearInterval(loadingInterval);

                return {
                    sentence: data.sentence,
                    gap_filling: data.gap_filling || data.sentence
                };
            } catch (error) {
                console.error('Error:', error);
                // 恢复按钮状态
                generateBtn.disabled = false;
                generateBtn.style.opacity = '1';
                generateBtn.style.cursor = 'pointer';
                clearInterval(loadingInterval);
                generateBtn.disabled = false;
                generateBtn.style.opacity = '1';
                generateBtn.style.cursor = 'pointer';
                return `This is a sample sentence containing the word ${word}.`;
            }
        }

        // 更新句子显示
        function updateSentenceDisplay() {
            let displayText = sentence.gap_filling;
            words.forEach((word, index) => {
                const filledWord = filledWords.get(index);
                if (filledWord) {
                    displayText = displayText.replace('___', 
                        `<span class="filled-word" data-index="${index}">${filledWord}</span>`);
                } else {
                    displayText = displayText.replace('___', 
                        '<span class="blank"></span>');
                }
            });
            sentenceDisplay.innerHTML = displayText;

            // 为填入的单词添加点击事件
            document.querySelectorAll('.filled-word').forEach(elem => {
                elem.addEventListener('click', () => {
                    const index = parseInt(elem.dataset.index);
                    const word = filledWords.get(index);
                    filledWords.delete(index);
                    updateSentenceDisplay();
                    updateWordChoices();
                });
            });

            // 检查是否完成所有单词
            if (filledWords.size === words.length) {
                // 构建用户填入的完整句子
                let userSentence = sentence.gap_filling;
                for (let [index, word] of filledWords) {
                    userSentence = userSentence.replace('___', word);
                }
                console.log('用户填入的完整句子:', userSentence);

                
                // 比较用户的句子与原始句子是否完全匹配
                const allCorrect = userSentence === sentence.sentence;

                if (allCorrect) {
                    victorySound.play();
                    victoryEffect.style.display = 'block';
                    victoryEffect.innerHTML = '';
                    createConfetti(victoryEffect, 100);
                    setTimeout(() => {
                        correctCount++;
                        document.getElementById('correctCount').textContent = correctCount;
                        victoryEffect.style.display = 'none';
                        victoryEffect.innerHTML = '';
                        alert(`🎉 胜利！\n正确: ${correctCount}次  错误: ${wrongCount}次`);
                        filledWords.clear();
                        updateSentenceDisplay();
                        updateWordChoices();
                    }, 3000);
                } else {
                    wrongSound.play();
                    wrongCount++;
                    document.getElementById('wrongCount').textContent = wrongCount;
                }
            }
        }

        // 更新单词选择区
        function updateWordChoices() {
            wordChoices.innerHTML = '';
            const usedWords = new Set(filledWords.values());
            words.forEach(word => {
                const btn = document.createElement('button');
                btn.textContent = word;
                btn.className = 'word-choice';
                if (usedWords.has(word)) {
                    btn.classList.add('used');
                } else {
                    btn.addEventListener('click', () => {
                        // 找到第一个未填的位置
                        for (let i = 0; i < words.length; i++) {
                            if (!filledWords.has(i)) {
                                

                                filledWords.set(i, word);
                                break;
                            }
                        }
                        updateSentenceDisplay();
                        updateWordChoices();
                    });
                }
                wordChoices.appendChild(btn);
            });
        }

        // 生成按钮点击事件
        generateBtn.addEventListener('click', async () => {
            words = wordInput.value.split('\n').filter(word => word.trim() !== '');
            correctCount = 0;
            wrongCount = 0;
            document.getElementById('correctCount').textContent = '0';
            document.getElementById('wrongCount').textContent = '0';
            
            sentence = await generateSentence(words);
            filledWords.clear();
            updateSentenceDisplay();
            updateWordChoices();
        });

        // 初始化
        words = wordInput.value.split('\n').filter(word => word.trim() !== '');
    </script>
</body>
</html>